package com.wyh.common.utils;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class QRCodeUntil {
    /**
     * 返回 解析二维码的 数据源
     */
    public static List<String> show(InputStream inputStream) {
        try {
            List<String> list = scanPDFForQRCode(inputStream);
            if (list != null) {
                return list;
            }
        } catch (IOException e) {
            log.info("传入pdf读取异常");
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    public static List<String> scanPDFForQRCode(InputStream pdfStream) throws IOException {

        PDDocument document = null;
        try {
            document = PDDocument.load(pdfStream);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            List<String> result = new ArrayList<>();

            for (int page = 0; page < document.getNumberOfPages(); page++) {
                BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300, ImageType.ARGB);
                String qrCodeText = decodeQRCode(image);
                List<String> extractedData = extractValidData(qrCodeText);

                if (!extractedData.isEmpty()) {
                    log.info("分割后的数据为: {}", extractedData);
                    result.addAll(extractedData);
                } else {
                    return new ArrayList<>();
                }
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pdfStream != null) {
                try {
                    pdfStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String decodeQRCode(BufferedImage image) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (NotFoundException e) {
            return null; // 数据为空
        }
    }

    // 截取数据截取合适数据
    public static List<String> extractValidData(String dataList) {
        List<String> newList = new ArrayList<>();
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
//            throw new IllegalArgumentException("PDF中没有数据");
        }

        String[] split = dataList.split(",");
        for (int i = 0; i < split.length; i++) {
            if (split[i].length() > 18) {
                // 添加第一个长度大于18的字符串
                newList.add(split[i]);
                // 添加后面的两个字符串，如果存在
                if (i + 1 < split.length) {
                    newList.add(split[i + 1]);
                }
                if (i + 2 < split.length) {
                    newList.add(split[i + 2]);
                }
                break; // 只需要第一个满足条件的数据，因此可以跳出当前循环
            }
        }
        return newList;
    }

    // 将 String 类型的时间数据转换为 LocalDate 类型
    public static LocalDate SswitchD(String str) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        try {
            return LocalDate.parse(str, formatter);
        } catch (DateTimeParseException e) {
            return null;
        }
    }

    // 将金额转换为 double 同时去掉符号
    public static Double SswitchNumber(String amount) {
        double v = Double.parseDouble(amount);
        double abs = Math.abs(v);
        return abs;
    }

}

